<?php

namespace app\admin\controller\yunfood;

use addons\yunfood\library\Backend;
use addons\yunfood\library\Super;
use addons\yunfood\model\Config;
use addons\yunfood\model\NoticeOffset;
use addons\yunfood\model\NoticeVoice;
use app\admin\model\yunfood\Order;
use app\admin\model\yunfood\Shop;
use app\admin\model\yunfood\ShopDesk;
use think\Db;
use think\Session;

/**
 * 工作台
 */
class Workbench extends Backend
{
    protected $noNeedRight = ['recentData', 'shopData', 'noticeData', 'voiceNotice'];

    /**
     * 查看
     */
    public function index()
    {
        try {
            Db::execute("SET @@sql_mode='';");
        } catch (\Exception $e) {
        }

        $shopList = Shop::getOptionList($this->getShopWhere(null, 'id'));
        $voiceNotice = Session::get('voiceNotice') ? 1 : 0;

        $this->view->assign([
            'shopList'    => $shopList,
            'voiceNotice' => $voiceNotice
        ]);
        $this->assignconfig('voiceNotice', $voiceNotice);

        return $this->view->fetch(null, ['time' => time()]);
    }

    /**
     * 最近下单数据
     */
    public function recentData()
    {
        $shopId = $this->request->request('shop_id');
        $query = Order::with(['orderItemListData', 'deskData'])->where(['shop_id' => $shopId])
            ->where('payment_status', '<>', Order::PAYMENT_STATUS_WAIT);
        $orderList = $query->order('id desc')->limit(8)->select();
        $orderList = Super::arrayGetSet($orderList, [
            'id',
            'order_no',
            'goods_list',
            'enjoy_type',
            'enjoy_type_text',
            'desk_number' => function ($item) {
                return $item->deskData->number ?? '';
            },
            'contact',
            'payment_time_text'
        ], true);

        $result = [
            'orderList' => $orderList,
        ];

        $this->success('', null, $result);
    }

    /**
     * 门店数据
     */
    public function shopData()
    {
        $shopId = $this->request->request('shop_id');
        $group = $this->request->request('group');
        $query = ShopDesk::where(['shop_id' => $shopId])->show();
        if ($group === ShopDesk::STATE_EMPTY) {
            $query->where('last_order_time < :time OR last_order_time is null', ['time' => time() - 3600 * 2]);
        } elseif ($group === ShopDesk::STATE_CONFIRM) {
            $query->where('last_order_time', '>=', time() - 3600 * 2)->where(['last_order_status' => 0]);
        } elseif ($group === ShopDesk::STATE_ING) {
            $query->where('last_order_time', '>=', time() - 3600 * 2)->where(['last_order_status' => 1]);
        }

        $deskList = $query->order('id asc')->select();
        $deskList = Super::arrayGetSet($deskList, [
            'id',
            'number',
            'state',
            'state_text',
            'last_order_time_text'
        ], true);

        $result = [
            'deskList' => $deskList,
        ];

        $this->success('', null, $result);
    }

    /**
     * 通知数据
     */
    public function noticeData()
    {
        $shopId = $this->request->request('shop_id');
        $sessionId = session_id();
        $result = [];

        // 获取最新订单【30秒内的订单】
        $query = Order::where(['shop_id' => $shopId])->where('payment_time', '>=', time() - 30);

        // 获取上次通知位置
        $noticeOffset = NoticeOffset::get([
            'shop_id'     => $shopId,
            'session_id'  => $sessionId,
            'source_type' => NoticeOffset::SOURCE_TYPE_NEW_ORDER
        ]);
        if ($noticeOffset) {
            $query->where('id', '>', $noticeOffset->source_id);
        }
        $newOrder = $query->order('id asc')->find();
        if ($newOrder) {
            $noticeConfig = Config::getGroupAttributes(Config::GROUP_NOTICE);
            if (! empty($noticeConfig['app_id']) && ! empty($noticeConfig['app_secret'])) {
                $result['title'] = '您有一个新的订单';
                $noticeVoice = NoticeVoice::createBaiduVoice($result['title']);
                $result['voice'] = $noticeVoice['src'];
            } else {
                $result['title'] = '您有一个新的订单';
                $result['voice'] = '/assets/addons/yunfood/file/voice_new_order.mp3';
            }
            if (! $noticeOffset) {
                $noticeOffset = new NoticeOffset();
                $noticeOffset->shop_id = $shopId;
                $noticeOffset->session_id = $sessionId;
                $noticeOffset->source_type = NoticeOffset::SOURCE_TYPE_NEW_ORDER;
                $noticeOffset->notice_times = 0;
            }
            $noticeOffset->notice_times++;
            $noticeOffset->source_id = $newOrder->id;
            $noticeOffset->save();
        }

        $this->success('', null, $result);
    }

    /**
     * 处理通知
     */
    public function voiceNotice()
    {
        $state = $this->request->request('state', 0);
        Session::set('voiceNotice', $state);

        $this->success('操作成功');
    }

    public function add()
    {
        return;
    }

    public function edit($ids = null)
    {
        return;
    }

    public function del($ids = null)
    {
        return;
    }

    public function multi($ids = null)
    {
        return;
    }
}
